package com.ruoyi.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.web.mapper.ProduceMapper;
import com.ruoyi.web.mapper.ReportMapper;
import com.ruoyi.web.vo.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportService extends ServiceImpl<ReportMapper, Report> implements IMesReportWork {
    @Resource
    private MesProducePieceMachineService producePieceMachineService;
    @Resource
    private ProducePieceService producePieceService;
    @Resource
    private MesMachineService mesMachineService;
    @Resource
    private MesCuttingGroupService mesCuttingGroupService;
    @Resource
    private MesBindingDailyService mesBindingDailyService;
    @Resource
    private ProduceMapper produceMapper;
    @Resource
    private ProducePrintService producePrintService;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 循环判断当前步骤的报工量不能大于上一步骤的报工量
     *
     * @param baseReport  抽象报工类
     * @param machineType 报工类型
     * @return 字符串
     */
    @Override
    public String checkMesReportPreviousStep(BaseReport baseReport, String machineType) {
        StringBuilder failureMsg = new StringBuilder();

        if (machineType.equals("2")) { // 印刷报工
//            List<ReportWork> reportWorkList = baseReport.reportWorkList;
//            if (reportWorkList != null && reportWorkList.size() != 0) {
//                for (ReportWork reportWork : reportWorkList) {
//                    MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
//                            .eq(MesProducePieceMachine::getPieceId, reportWork.getPieceId())
//                            .eq(MesProducePieceMachine::getMachineId, baseReport.getMachineId())
//                            .last("LIMIT 1")
//                    );
//
//                    BigDecimal first = reportWork.getPrintAmount().multiply(new BigDecimal(reportWork.getSheet()));
//                    BigDecimal second = reportWork.getLossCoefficient().add(new BigDecimal(1));
//
//                    // 轮转公式不乘以印张
//                    if (!reportWork.getPrintType().equals("1")) { // 转轮
//                        first = reportWork.getPrintAmount();
//                    }
//                    // 最大允许上报量 =（印数*印张）*（1+损耗系数）
//                    BigDecimal finalnum = first.multiply(second); // 最大允许上报量：(印张*印数)*(1+损耗系数)
//                    BigDecimal varTemp = new BigDecimal(1000);
//                    BigDecimal printAmount = reportWork.getPrintAmount();
//                    // 印数小于1000 ，本次允许的最大上报数量 等于 1000
//                    if (printAmount.compareTo(varTemp) < 0) {
//                        finalnum = new BigDecimal(1000);
//                    }
//
//                    // 当前步骤累积报工量
//                    BigDecimal currentTotalNum = producePieceMachine.getTotal();
//                    // 本次允许的最大上报数量 finalnum - currentTotalNum
//                    BigDecimal currentMaxNum = finalnum.subtract(currentTotalNum);
//                    currentMaxNum = currentMaxNum.setScale(0, RoundingMode.UP); // 向上取整
//                    if (reportWork.getFinishNum().compareTo(currentMaxNum) > 0) {
//                        failureMsg.append("品种：" + reportWork.getBreed() + ",贴标：" + reportWork.getLabeling() + ",当前报工量 " + reportWork.getFinishNum() + " 大于本次最大上报量 " + currentMaxNum);
//                    }
//
//                }
//            }
        } else if (machineType.equals("4")) { // 折页报工
            List<ReportWork> reportWorkList = baseReport.reportWorkList;
            if (reportWorkList != null && reportWorkList.size() != 0) {
                for (ReportWork reportWork : reportWorkList) {
                    Map<String, String> params = selectPreviousStep(reportWork.getPieceId(), baseReport.getMachineId(), reportWork.getFinishNum());
                    if (Integer.parseInt(params.get("preStep")) > -1) { // 如果有上一步往下进行
                        BigDecimal currentTotalNum = new BigDecimal(params.get("currentTotalNum"));
                        BigDecimal previousTotalNum = new BigDecimal(params.get("previousTotalNum"));
                        String sheet = StringUtils.isEmpty(reportWork.getSheet()) ? "0" : reportWork.getSheet();
                        BigDecimal decimalSheet = new BigDecimal(sheet);
                        BigDecimal decimalBZ = new BigDecimal(1);
                        int comparisonResult = decimalSheet.compareTo(decimalBZ);
                        if (comparisonResult < 0) {//Integer.parseInt(sheet)< 1
                            previousTotalNum = previousTotalNum.divide(decimalSheet);
                        }
                        if (currentTotalNum.compareTo(previousTotalNum) > 0) {
                            failureMsg.append("品种：" + reportWork.getBreed() + ",贴标：" + reportWork.getLabeling() + ",当前步骤的累计报工量 " + currentTotalNum + " 大于上一步骤累计报工量 " + previousTotalNum);
                        }
                    }
                }
            }
        } else if (machineType.equals("7")) { // 覆膜报工
            List<MesCoveringWork> coveringWorkList = baseReport.orderWorkList;
            if (coveringWorkList != null && coveringWorkList.size() != 0) {
                for (MesCoveringWork coveringWork : coveringWorkList) {
                    Map<String, String> params = selectPreviousStep(coveringWork.getPieceId(), baseReport.getMachineId(), coveringWork.getCompleteCount());
                    if (Integer.parseInt(params.get("preStep")) > -1) { // 如果有上一步往下进行
                        BigDecimal currentTotalNum = new BigDecimal(params.get("currentTotalNum"));
                        BigDecimal previousTotalNum = new BigDecimal(params.get("previousTotalNum"));
                        if (currentTotalNum.compareTo(previousTotalNum) > 0) {
                            ProducePiece producePiece = producePieceService.getOne(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getPieceId, coveringWork.getPieceId()));
                            ProducePrint producePrint = producePrintService.getOne(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getPrintId, producePiece.getPrintId()));
                            failureMsg.append("品种：" + producePrint.getBreed() + ",贴标：" + producePrint.getLabeling() + ",当前步骤的累计报工量 " + currentTotalNum + " 大于上一步骤累计报工量 " + previousTotalNum);
                        }
                    }
                }
            }
        } else if (machineType.equals("3")) { // 装订报工
            List<MesBindingDailyDetail> bindingWorkList = baseReport.bindingDailyDetails;
            if (bindingWorkList != null && bindingWorkList.size() != 0) {
                for (MesBindingDailyDetail detail : bindingWorkList) {
                    // 查询该产品对应印刷贴,排除 1 2 整代 半代 的
                    List<String> strList = Arrays.asList("1", "2");
                    //根据生产单和产品查询贴集合
                    TwoValues twoValues = mesBindingDailyService.getPieceList(detail.getProduceId(), detail.getOrderProductId(), strList);
                    if (StringUtils.isNotEmpty(twoValues.value1)) {
                        failureMsg.append(twoValues.value1.toString());
                        break;
                    }
                    List<ProducePiece> pieceList = twoValues.value2;
                    if (!pieceList.isEmpty()) {
                        // 贴数id集合
                        List<String> pieceIds = pieceList.stream().map(it -> it.getPieceId()).collect(Collectors.toList());
                        String pieceIdsStr = String.join(",", pieceIds);
                        BigDecimal minNum = produceMapper.getMinProducePieceMachineByIds(pieceIdsStr);
                        for (ProducePiece item : pieceList) {
                            BigDecimal currentTotalNum = minNum;
                            BigDecimal previousTotalNum = detail.getTotalNum();
                            if (currentTotalNum.compareTo(previousTotalNum) > 0) {
                                ProducePrint producePrint = producePrintService.getOne(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getPrintId, item.getPrintId()));
                                failureMsg.append("品种：" + producePrint.getBreed() + ",贴标：" + producePrint.getLabeling() + ",当前累计报工量 " + currentTotalNum + " 大于最小报工量 " + previousTotalNum);
                            }
                        }
                    }
                }
            }

        } else {  // 裁切报工
            List<ReportWork> reportWorkList = baseReport.reportWorkList;
            if (reportWorkList != null && reportWorkList.size() != 0) {
                for (ReportWork reportWork : reportWorkList) {
                    Map<String, String> params = selectPreviousStep(reportWork.getPieceId(), baseReport.getMachineId(), reportWork.getFinishNum());
                    if (Integer.parseInt(params.get("preStep")) > -1) { // 如果有上一步往下进行
                        BigDecimal currentTotalNum = new BigDecimal(params.get("currentTotalNum"));
                        BigDecimal previousTotalNum = new BigDecimal(params.get("previousTotalNum"));
                        if (currentTotalNum.compareTo(previousTotalNum) > 0) {
                            failureMsg.append("品种：" + reportWork.getBreed() + ",贴标：" + reportWork.getLabeling() + ",当前步骤的累计报工量 " + currentTotalNum + " 大于上一步骤累计报工量 " + previousTotalNum);
                        }
                    }
                }
            }
        }
        return failureMsg.toString();
    }

    /**
     * 查询当前步骤的累计报工量和一步骤的累计报工量相关信息
     *
     * @param pieceId   贴数id
     * @param machineId 机台id
     * @return 当前步骤累计报工量 + 本次报工量，上一步累计报工量，当前步骤，上一步骤
     */
    private Map<String, String> selectPreviousStep(String pieceId, String machineId, BigDecimal completeCount) {
        Map<String, String> params = new HashMap<>();//存储最各类型任务量最少的机台
        // 查询该机台该贴当前步骤
        MesProducePieceMachine producePieceMachineCurrent = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
                .eq(MesProducePieceMachine::getPieceId, pieceId)
                .eq(MesProducePieceMachine::getMachineId, machineId)
                .last("LIMIT 1")
        );
        Integer currentStep = 0;
        Integer preStep = 0;
        if (producePieceMachineCurrent != null) {
            currentStep = producePieceMachineCurrent.getStep();
            preStep = producePieceMachineCurrent.getStep() - 1;
        }
        // 查询该贴上一步骤
        MesProducePieceMachine producePieceMachinePrevious = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
                .eq(MesProducePieceMachine::getPieceId, pieceId)
                .eq(MesProducePieceMachine::getStep, preStep)
                .last("LIMIT 1")
        );
        BigDecimal currentTotalNum = BigDecimal.ZERO;
        BigDecimal previousTotalNum = BigDecimal.ZERO;
        if (producePieceMachineCurrent != null) {
            BigDecimal currentTotalNumTemp = selectTotalNum(pieceId, machineId, "");
            // BigDecimal currentTotalNumTemp = (producePieceMachineCurrent.getTotal() == null ? BigDecimal.ZERO : producePieceMachineCurrent.getTotal());
            currentTotalNum = currentTotalNumTemp.add(completeCount); // 当前步骤累积报工量 + 本次报工量
        }

        if (producePieceMachinePrevious != null)
            //previousTotalNum = (producePieceMachinePrevious.getTotal() == null ? BigDecimal.ZERO : producePieceMachinePrevious.getTotal());
            previousTotalNum = selectTotalNum(pieceId, producePieceMachinePrevious.getMachineId(), "");

        params.put("currentTotalNum", currentTotalNum.toString());
        params.put("previousTotalNum", previousTotalNum.toString());
        params.put("currentStep", currentStep.toString());
        params.put("preStep", preStep.toString());

        return params;
    }

    /**
     * 循环判断当前报工数量大于剩余可报工量
     *
     * @param baseReport  抽象报工类
     * @param machineType 报工类型
     * @return 字符串
     */
    @Override
    public String selectMesReportSurplus(BaseReport baseReport, String machineType) {
        StringBuilder failureMsg = new StringBuilder();
        MesMachine mesMachine = mesMachineService.getById(baseReport.getMachineId());
        if (machineType.equals("7")) { // 覆膜报工
            List<MesCoveringWork> coveringWorkList = baseReport.orderWorkList;
            if (coveringWorkList != null && coveringWorkList.size() != 0) {
                for (MesCoveringWork coveringWork : coveringWorkList) {
                    // 报工量，覆多少膜
                    BigDecimal finishNum = coveringWork.getCompleteCount() == null ? new BigDecimal("0") : coveringWork.getCompleteCount();
                    ProducePiece producePiece = producePieceService.getById(coveringWork.getPieceId());
                    String mes = checkSurplus(finishNum, producePiece.getPrintAmount(), coveringWork.getPieceId(), mesMachine.getType());
                    if (StringUtils.isNotEmpty(mes)) {
                        failureMsg.append(mes);
                    }
                }
            }
        }
        if (machineType.equals("3")) { // 装订报工
        } else {
            List<ReportWork> reportWorkList = baseReport.reportWorkList;
            if (reportWorkList != null && reportWorkList.size() != 0) {
                for (ReportWork reportWork : reportWorkList) {
                    // 报工量，报多少工
                    BigDecimal finishNum = reportWork.getFinishNum() == null ? new BigDecimal("0") : reportWork.getFinishNum();
                    ProducePiece producePiece = producePieceService.getById(reportWork.getPieceId());
                    String mes = checkSurplus(finishNum, producePiece.getPrintAmount(), reportWork.getPieceId(), mesMachine.getType());
                    if (StringUtils.isNotEmpty(mes)) {
                        failureMsg.append(mes);
                    }
                }
            }
        }
        return failureMsg.toString();
    }

    /**
     * 判断当前报工数量大于剩余可报工量
     *
     * @param finishNum   完工数量
     * @param printAmount 印数
     * @param pieceId     贴数id
     * @param machineType 机型
     * @return 字符串
     */
    private String checkSurplus(BigDecimal finishNum, BigDecimal printAmount, String pieceId, String machineType) {
        String returnMsg = "";
        List<MesProducePieceMachine> list1 = producePieceMachineService.list(new QueryWrapper<MesProducePieceMachine>()
                .lambda()
                .eq(MesProducePieceMachine::getPieceId, pieceId)
                .eq(MesProducePieceMachine::getMachineType, machineType));
        BigDecimal total = BigDecimal.ZERO;
        if (list1.size() > 0) {
            total = list1.get(0).getTotal();
        }

        if (finishNum.compareTo(printAmount.subtract(total)) > 0) {
            returnMsg = "贴数id：" + pieceId + "报工数量大于剩余可报工量";
        }
        return returnMsg;
    }

    /**
     * 循环查询累计上报数量和最大上报数量
     *
     * @param produce     抽象报工类
     * @param machineId   机台id
     * @param machineType 机台类型
     * @return 字符串
     */
    @Override
    public String selectMesReportTotalNum(Produce produce, String machineId, String machineType,String bindingType) {
        if (machineType.equals("2")) { // 印刷报工
            List<ProducePiece> pieceList = produce.getProducePieceList();
            if (pieceList.size() > 0) {
                for (ProducePiece piece : pieceList) {
                    MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
                            .eq(MesProducePieceMachine::getPieceId, piece.getPieceId())
                            .eq(MesProducePieceMachine::getMachineId, machineId)
                            .last("LIMIT 1")
                    );
                    if (producePieceMachine != null) {
                        ProducePrint producePrint = producePrintService.getOne(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getPrintId, piece.getPrintId()));
                        // 查询另行加放
                        String lxjfStr = StringUtils.isEmpty(producePrint.getLxjf()) ? "0" : producePrint.getLxjf();
                        // 定义印张
                        String sheetStr = StringUtils.isEmpty(piece.getSheet()) ? "0" : piece.getSheet();
                        BigDecimal sheet = new BigDecimal(sheetStr);
                        // 定义印数
                        BigDecimal printAmount = piece.getPrintAmount();
                        // (印数*印张)
                        BigDecimal first = printAmount.multiply(sheet);
                        // (1+损耗系数)
                        BigDecimal second = piece.getLossCoefficient().add(new BigDecimal(1));
                        // 另行加放
                        BigDecimal third = new BigDecimal(lxjfStr);
                        // 定义最大允许上报数量
                        BigDecimal finalnum = new BigDecimal(0);
                        // 印刷方式 1平张，2轮转
                        String printType = piece.getPrintType();

                        // 轮转公式不乘以印张
                        if (printType.equals("1")) {  // 平张
                            // 最大允许上报量：(印数*印张)*(1+损耗系数)+另行加放
                            finalnum = first.multiply(second).add(third);
                        } else {  // 卷筒
                            //
                            if (sheet.compareTo(new BigDecimal(1)) == 0 && printAmount.compareTo(new BigDecimal(1000)) < 0) {
                                finalnum = first.multiply(second).add(third);
                            } else if (sheet.compareTo(new BigDecimal(1)) < 0 && printAmount.compareTo(new BigDecimal(1000)) < 0) {
                                first = piece.getPrintAmount();   // 不乘印张
                                finalnum = first.multiply(second).add(third);
                            } else if (sheet.compareTo(new BigDecimal(1)) == 0 && printAmount.compareTo(new BigDecimal(1000)) > 0) {
                                finalnum = first.multiply(second).add(third);
                            } else if (sheet.compareTo(new BigDecimal(1)) < 0 && printAmount.compareTo(new BigDecimal(1000)) > 0) {
                                first = piece.getPrintAmount();   // 不乘印张
                                finalnum = first.multiply(second).add(third);
                            }
                        }

//                        BigDecimal varTemp = new BigDecimal(1000);
//                        BigDecimal printAmount = piece.getPrintAmount();
//                        // 印数小于1000 ，本次允许的最大上报数量 等于 1000
//                        if (printAmount.compareTo(varTemp) < 0) {
//                            finalnum = new BigDecimal(1000);
//                        }

                        // 累计上报数量
                        BigDecimal currentTotalNum = selectTotalNum(piece.getPieceId(), machineId, "");
                        BigDecimal currentTotalNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整
                        // 本次允许的最大上报数量： finalnum - currentTotalNum
                        BigDecimal currentMaxNum = finalnum.subtract(currentTotalNum);
                        BigDecimal currentMaxNumUp = currentMaxNum.setScale(0, RoundingMode.UP); // 向上取整
                        // 负数返回0
                        currentTotalNumUp = currentTotalNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentTotalNumUp;
                        currentMaxNumUp = currentMaxNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentMaxNumUp;
                        piece.setTotalNum(currentTotalNumUp);  // 累计上报量
                        piece.setMaxNum(currentMaxNumUp); // 本次最大上报量

                    }
                }
            }
        } else if (machineType.equals("4")) { // 折页报工
            List<ProducePiece> pieceList = produce.getProducePieceList();
            if (pieceList.size() > 0) {
                for (ProducePiece piece : pieceList) {
                    MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
                            .eq(MesProducePieceMachine::getPieceId, piece.getPieceId())
                            .eq(MesProducePieceMachine::getMachineId, machineId)
                            .last("LIMIT 1")
                    );
                    if (producePieceMachine != null) {
                        // 印刷的累计上报数量
                        BigDecimal currentTotalNumYS = selectTotalNum(piece.getPieceId(), "", "1");

                        // 折页的累计上报数量
                        BigDecimal currentTotalNum = selectTotalNum(piece.getPieceId(), machineId, "");

                        // 定义印张
                        String sheetStr = StringUtils.isEmpty(piece.getSheet()) ? "0" : piece.getSheet();
                        BigDecimal sheet = new BigDecimal(sheetStr);

                        // 半代
                        if (sheet.compareTo(new BigDecimal(1)) < 0) {
                            currentTotalNumYS = currentTotalNumYS.divide(sheet);
                        }
                        BigDecimal currentTotalNumYSUp = currentTotalNumYS.setScale(0, RoundingMode.UP); // 向上取整

                        // 本次允许的最大上报数量： currentTotalNumYS - currentTotalNum
                        BigDecimal currentMaxNum = currentTotalNumYS.subtract(currentTotalNum);
                        BigDecimal currentMaxNumUp = currentMaxNum.setScale(0, RoundingMode.UP); // 向上取整

                        // 负数返回0
                        currentTotalNumYSUp = currentTotalNumYSUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentTotalNumYSUp;
                        currentMaxNumUp = currentMaxNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentMaxNumUp;
                        piece.setTotalNum(currentTotalNumYSUp);  // 累计上报量
                        piece.setMaxNum(currentMaxNumUp); // 本次最大上报量
                    }
                }
            }
        } else if (machineType.equals("7")) { // 覆膜报工
            List<ProducePiece> pieceList = produce.getProducePieceList();
            if (pieceList.size() > 0) {
                for (ProducePiece piece : pieceList) {
                    MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
                            .eq(MesProducePieceMachine::getPieceId, piece.getPieceId())
//                            .eq(MesProducePieceMachine::getMachineId, machineId) 20240701 覆膜两个机台可以互相选择，因此不过滤机台，并且一次报工完
                            .last("LIMIT 1")
                    );
                    if (producePieceMachine != null) {
                        // 印刷的累计上报数量
                        BigDecimal currentTotalNumYS = selectTotalNum(piece.getPieceId(), "", "1");
                        BigDecimal currentTotalNumYSUp = currentTotalNumYS.setScale(0, RoundingMode.UP); // 向上取整
                        // 覆膜的累计上报数量
                        BigDecimal currentTotalNum = selectTotalNum(piece.getPieceId(), machineId, "");

                        // 本次允许的最大上报数量： currentTotalNumYS - currentTotalNum
                        BigDecimal currentMaxNum = currentTotalNumYS.subtract(currentTotalNum);
                        BigDecimal currentMaxNumUp = currentMaxNum.setScale(0, RoundingMode.UP); // 向上取整

                        // 负数返回0
                        currentTotalNumYSUp = currentTotalNumYSUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentTotalNumYSUp;
                        currentMaxNumUp = currentMaxNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentMaxNumUp;
                        piece.setTotalNum(currentTotalNumYSUp);  // 印刷累计上报量
                        piece.setMaxNum(currentMaxNumUp); // 本次最大上报量
                    }
                }
            }
        } else if (machineType.equals("3")) { // 装订报工
            List<ProduceProduct> productList = produce.getProduceProductList();
            if (productList.size() > 0) {
                for (ProduceProduct product : productList) {
                    // 定义最大允许上报数量
                    BigDecimal finalnum = new BigDecimal(0);
                    // 定义订单数量
                    String produceCountStr = StringUtils.isEmpty(product.getProduceCount().toString()) ? "0" : product.getProduceCount().toString();
                    BigDecimal produceCount = new BigDecimal(produceCountStr);

                    // 最大允许上报量：订单数量*1.003
                    finalnum = produceCount.multiply(new BigDecimal(1.003));
                    // 累计上报量
                    BigDecimal currentTotalNum = selectTotalNumBinding(product.getProductId(), machineId, bindingType);
                    BigDecimal currentTotalNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整

                    // 本次允许的最大上报数量： finalnum - currentTotalNum
                    currentTotalNum = finalnum.subtract(currentTotalNum);
                    BigDecimal currentMaxNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整

                    // 负数返回0
                    currentTotalNumUp = currentTotalNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentTotalNumUp;
                    currentMaxNumUp = currentMaxNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentMaxNumUp;
                    product.setTotalNum(currentTotalNumUp);  // 累计上报量
                    product.setMaxNum(currentMaxNumUp); // 最大上报量


//                    // 查询该产品对应印刷贴,排除 1 2 整代 半代 的
//                    List<String> strList = Arrays.asList("1", "2");
//                    //根据生产单和产品查询贴集合
//                    TwoValues twoValues = mesBindingDailyService.getPieceList(product.getProduceId(), product.getOrderProductId(), strList);
//                    if (StringUtils.isNotEmpty(twoValues.value1)) {
//                        return twoValues.value1.toString();
//                    }
//                    List<ProducePiece> pieceListAll = twoValues.value2;
//                    if (pieceListAll.size() == 0) {
//                        return "生产印刷单没有贴的信息";
//                    }
//                    MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
//                            .eq(MesProducePieceMachine::getPieceId, pieceListAll.get(0).getPieceId())
//                            .eq(MesProducePieceMachine::getMachineId, machineId)
//                            .last("LIMIT 1")
//                    );
//                    if (producePieceMachine != null) {
//                        // 定义印数
//                        BigDecimal printAmount = pieceListAll.get(0).getPrintAmount();
//                        BigDecimal currentTotalNum = selectTotalNumBinding(pieceListAll.get(0).getPieceId(), machineId, "");
//                        BigDecimal currentTotalNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整
//                        // 本次允许的最大上报数量： printAmount - currentTotalNum
//                        currentTotalNum = printAmount.subtract(currentTotalNum);
//                        BigDecimal currentMaxNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整
//
//                        // 负数返回0
//                        currentTotalNumUp = currentTotalNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentTotalNumUp;
//                        currentMaxNumUp = currentMaxNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentMaxNumUp;
//                        product.setTotalNum(currentTotalNumUp);  // 累计上报量
//                        product.setMaxNum(currentMaxNumUp); // 最大上报量
//
//                    }
                }
            }
        } else if (machineType.equals("5") || machineType.equals("6")) { // 裁切报工
            List<ProducePiece> pieceList = produce.getProducePieceList();
            if (pieceList.size() > 0) {
                for (ProducePiece piece : pieceList) {
                    MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
                            .eq(MesProducePieceMachine::getPieceId, piece.getPieceId())
                            .eq(MesProducePieceMachine::getMachineId, machineId)
                            .last("LIMIT 1")
                    );
                    if (producePieceMachine != null) {
                        // 定义印数
                        BigDecimal printAmount = piece.getPrintAmount();
                        BigDecimal currentTotalNum = selectTotalNum(piece.getPieceId(), machineId, "");
                        BigDecimal currentTotalNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整
                        // 本次允许的最大上报数量： printAmount - currentTotalNum
                        currentTotalNum = printAmount.subtract(currentTotalNum);
                        BigDecimal currentMaxNumUp = currentTotalNum.setScale(0, RoundingMode.UP); // 向上取整

                        // 负数返回0
                        currentTotalNumUp = currentTotalNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentTotalNumUp;
                        currentMaxNumUp = currentMaxNumUp.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal(0) : currentMaxNumUp;
                        // piece.setTotalNum(currentTotalNumUp);  // 累计上报量
                        piece.setMaxNum(currentMaxNumUp);      // 本次最大上报量
                    }
                }
            }
        }
        return "";
    }

    /**
     * 实时查询累积上报量
     *
     * @param pieceId   贴id
     * @param machineId 机台id
     * @param type      报工类型
     * @return 字符串
     */
    public BigDecimal selectTotalNum(String pieceId, String machineId, String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("pieceId", pieceId);
        map.put("machineId", machineId);
        map.put("type", type);
        BigDecimal totalNum = reportMapper.selectTotalNum(map);
        return totalNum;
    }

    /**
     * 实时查询装订累积上报量
     *
     * @param productId   产品id
     * @param machineId 机台id
     * @param type      报工类型
     * @return 字符串
     */
    public BigDecimal selectTotalNumBinding(String productId, String machineId, String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId);
        map.put("machineId", machineId);
        map.put("type", type);
        BigDecimal totalNum = reportMapper.selectTotalNumBinding(map);
        return totalNum;
    }

    // 机台用纸令数查询
    public List<ReportWork> getRealityLing(ReportWork reportWork1){
        // 查询数据
        if(StringUtils.isEmpty(reportWork1.getDate())){
            throw new BaseException("未获取到日期信息");
        }
        Report report = new Report();
        // 处理日期
        String date = reportWork1.getDate();
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 开始日期
        try {
            Date parse = dateFormat.parse(year + "-" + month + "-01 00:00:00");
            report.setBeginDate(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 截止日期
        if(month == 12){
            try {
                Date parse = dateFormat.parse((year + 1) + "-01-01 00:00:00");
                report.setEndDate(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            try {
                Date parse = dateFormat.parse(year + "-" + (month + 1) + "-01 00:00:00");
                report.setEndDate(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        // 查询印刷报工
        List<ReportWork> reportWorks = reportMapper.selectRealityLing(report);
        // 查询装订报工
        List<ReportWork> reportWorks2 = reportMapper.selectBindingDailyg(report);
        if(reportWorks.size() == 0 && reportWorks2.size() == 0){
            return reportWorks;
        }
        // 查询字典
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("ems_machine_info_size");// 板材尺寸
        List<SysDictData> dataList = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> printTypeMap = dataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 处理印数报工
        Map<String, List<ReportWork>> map = reportWorks.stream().collect(Collectors.groupingBy(ReportWork::getWorkshopName));
        ArrayList<ReportWork> list = new ArrayList<>();
        for (String s : map.keySet()) {
            List<ReportWork> reportWorks1 = map.get(s);
            BigDecimal decimal = new BigDecimal(0);
            for (ReportWork work : reportWorks1) {
                if(work.getRealityLing() != null){
                    decimal = decimal.add(work.getRealityLing());
                }
                if(StringUtils.isNotEmpty(work.getPrintType())){
                    if("1".equals(work.getPrintType())){
                        work.setPrintType("平张");
                    }else {
                        work.setPrintType("卷筒");
                    }
                }
                if(work.getSize() != null){
                    work.setSize(printTypeMap.get(work.getSize()));
                }
            }
            ReportWork reportWork = new ReportWork();
            reportWork.setWorkshopName("合计");
            reportWork.setRealityLing(new BigDecimal(decimal.stripTrailingZeros().toPlainString()));
            list.addAll(reportWorks1);
            list.add(reportWork);
        }
        // 处理装订报工
        Map<String, List<ReportWork>> map2 = reportWorks2.stream().collect(Collectors.groupingBy(ReportWork::getWorkshopName));
        ArrayList<ReportWork> list2 = new ArrayList<>();
        for (String s : map2.keySet()) {
            List<ReportWork> reportWorks1 = map2.get(s);
            BigDecimal decimal = new BigDecimal(0);
            for (ReportWork work : reportWorks1) {
                if(work.getRealityLing() != null){
                    decimal = decimal.add(work.getRealityLing());
                }
                if(StringUtils.isNotEmpty(work.getPrintType())){
                    if("1".equals(work.getPrintType())){
                        work.setPrintType("平张");
                    }else {
                        work.setPrintType("卷筒");
                    }
                }
                if(work.getSize() != null){
                    work.setSize(printTypeMap.get(work.getSize()));
                }
            }
            ReportWork reportWork = new ReportWork();
            reportWork.setWorkshopName("合计");
            reportWork.setRealityLing(new BigDecimal(decimal.stripTrailingZeros().toPlainString()));
            list2.addAll(reportWorks1);
            list2.add(reportWork);
        }
        // 合并印刷报工以及装订报工
        list.addAll(list2);
        return list;
    }

    // 机台用纸令数导出
    public AjaxResult exportRealityLing(ReportWork reportWork){
        // 查询数据
        List<ReportWork> list = getRealityLing(reportWork);
        if(list == null || list.size() == 0){
            return AjaxResult.error("导出的数据为空");
        }
        //创建Workbook对象(excel的文档对象)
        SXSSFWorkbook swb = new SXSSFWorkbook(100);
        //建立新的sheet页
        SXSSFSheet sheet = swb.createSheet("机台用纸令数");

        //标题样式
        CellStyle titleStyle = swb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        titleStyle.setFillForegroundColor((short) 22);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font font = swb.createFont();
        font.setBold(true);
        titleStyle.setFont(font);

        //标题样式
        CellStyle titleStyle2 = swb.createCellStyle();
        titleStyle2.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        titleStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        titleStyle2.setFillForegroundColor((short) 43);
        titleStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle2.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle2.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle2.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle2.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font font2 = swb.createFont();
        font2.setBold(true);
        titleStyle2.setFont(font2);

        //单元格样式
        CellStyle cellStyle = swb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font cellFont = swb.createFont();
        cellStyle.setFont(cellFont);

        //【4】创建标题行
        SXSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("车间");
        row.createCell(1).setCellValue("机台");
        row.createCell(2).setCellValue("印刷方式");
        row.createCell(3).setCellValue("板材尺寸");
        row.createCell(4).setCellValue("机长");
        row.createCell(5).setCellValue("实际用纸令数");

        for (int i = 0; i <= 5; i++) {
            //设置表格列宽度为5000个字节
            sheet.setColumnWidth(i, 5000);
            //设置单元格样式
            row.getCell(i).setCellStyle(titleStyle);
        }

        // 创建数据
        int i = 1;
        for (ReportWork workShop : list) {
            row = sheet.createRow(i);
            row.createCell(0).setCellValue(workShop.getWorkshopName());
            row.createCell(1).setCellValue(workShop.getMachineName());
            row.createCell(2).setCellValue(workShop.getPrintType());
            row.createCell(3).setCellValue(workShop.getSize());
            row.createCell(4).setCellValue(workShop.getHeadName());
            row.createCell(5).setCellValue(workShop.getRealityLing().stripTrailingZeros().toPlainString());
            // 设置样式
            for (int j = 0; j <= 5; j++) {
                if("合计".equals(workShop.getWorkshopName())){
                    row.getCell(j).setCellStyle(titleStyle2);
                }else {
                    row.getCell(j).setCellStyle(cellStyle);
                }

            }
            i++;
        }

        OutputStream out = null;
        try {
            // 创建文件名
            String filename = UUID.randomUUID().toString() + "机台用纸令数导出.xlsx";
            String downloadPath = RuoYiConfig.getDownloadPath() + filename;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            out = new FileOutputStream(downloadPath);
            swb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！" + e.getMessage());
        } finally {
            if (swb != null) {
                try {
                    swb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
